import React, { PureComponent } from 'react'
import { connect } from 'dva'
import { Select, TreeSelect, Row, Col, Form, Input, Button, DatePicker } from 'antd'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item
const { TreeNode } = TreeSelect
const { Option } = Select
const { RangePicker } = DatePicker

@connect(({ loading, property, propExpired, department, account }) => ({
  department,
  account,
  propExpired,
  property,
  loading: loading.models.property || loading.models.propExpired,
}))
@Form.create()
export default class PropExpiredSearchForm extends PureComponent {
  // 组件加载完成后加载数据
  componentDidMount() {
    const { dispatch } = this.props

    const propSelectKeys = ['property_status', 'property_class', 'location_seat', 'property_type']
    // 获取状态select数据
    // 资产分类select数据
    // 获取位置select数据
    // 资产类型select数据
    propSelectKeys.forEach(key => {
      dispatch({
        type: 'property/fetchSelectPropData',
        payload: {
          type: key,
        },
      })
    })

    // 部门数据
    dispatch({
      type: 'department/listOrg',
    })
    // 用户
    dispatch({
      type: 'account/fetch',
      payload: {
        pageSize: 100,
      },
    })
  }

  // 重置事件
  handleFormReset = () => {
    const { form, formResetCallback } = this.props
    form.resetFields()

    formResetCallback()
  }

  // 搜索事件
  handleSearch = e => {
    e.preventDefault()

    const { form, searchCallback } = this.props
    // 表单验证
    form.validateFields((err, fieldsValue) => {
      if (err) return

      const values = {
        ...fieldsValue,
      }
      const { rangeValue } = fieldsValue
      delete values.rangeValue
      values.startDate =
        rangeValue && rangeValue[0] ? rangeValue[0].format('YYYY-MM-DD') : undefined
      values.endDate = rangeValue && rangeValue[1] ? rangeValue[1].format('YYYY-MM-DD') : undefined

      searchCallback(values)
    })
  }

  handleDepChange = value => {
    const { resetFields } = this.props.form
    this.props.dispatch({
      type: 'account/fetchUsersByOrgId',
      payload: value,
      callback: () => {
        resetFields(['useOperator'])
      },
    })
  }

  // 资产属性下拉option
  renderOptionNodes(type) {
    const data = this.props.property[type]
    return data.map(item => (
      <Option key={item.id} value={item.keyName}>
        {item.keyValue}
      </Option>
    ))
  }

  // 渲染部门树节点
  renderTreeNodes(data) {
    return data
      .map(item => {
        if (item.status === '0001') {
          if (item.children) {
            return (
              // 此处查询用 id
              <TreeNode title={item.name} key={item.id} value={item.id}>
                {this.renderTreeNodes(item.children)}
              </TreeNode>
            )
          }
          return <TreeNode title={item.name} key={item.id} value={item.id} />
        }
        return null
      })
      .filter(item => item || false)
  }

  renderSearchBtn() {
    const { loading } = this.props
    return (
      <div style={{ marginLeft: 'auto' }}>
        <Button type="primary" htmlType="submit" loading={loading}>
          查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} loading={loading}>
          重置
        </Button>
      </div>
    )
  }

  // 简单搜索条件
  render() {
    const { usersByOrgId } = this.props.account
    const depData = this.props.department.data
    const { getFieldDecorator } = this.props.form
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="*资产编码">
              {getFieldDecorator('zcCode')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="*资产名称">
              {getFieldDecorator('zcName')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="资产分类">
              {getFieldDecorator('zcClass')(
                <Select placeholder="请选择" allowClear>
                  {this.renderOptionNodes('property_class')}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="资产类型">
              {getFieldDecorator('zcType')(
                <Select placeholder="请选择" allowClear>
                  {this.renderOptionNodes('property_type')}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="*型号规格">
              {getFieldDecorator('specification')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所在位置">
              {getFieldDecorator('zcSeat')(
                <Select placeholder="请选择" allowClear>
                  {this.renderOptionNodes('location_seat')}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="使用部门">
              {getFieldDecorator('orgId')(
                <TreeSelect
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  showCheckedStrategy={TreeSelect.SHOW_ALL}
                  allowClear
                  showSearch
                  treeNodeFilterProp="title"
                  placeholder="请选择所属部门节点"
                  onChange={this.handleDepChange}
                >
                  {this.renderTreeNodes(depData)}
                </TreeSelect>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用人">
              {getFieldDecorator('useOperator')(
                <Select placeholder="根据部门请选择" allowClear>
                  {usersByOrgId.map(item => (
                    <Option key={item.id} value={item.id}>
                      {item.realityName}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" allowClear>
                  {this.renderOptionNodes('property_status')}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="提醒时间">
              {getFieldDecorator('rangeValue')(<RangePicker></RangePicker>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="*SN码">
              {getFieldDecorator('sn')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="*RFID码">
              {getFieldDecorator('rfidCode')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 15 }}>
          {this.renderSearchBtn()}
        </div>
      </Form>
    )
  }
}
